package org.jeecg.alibaba.api;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.jeecg.alibaba.utils.HttpUtils;
import org.jeecg.common.util.oConvertUtils;

import java.util.HashMap;
import java.util.Map;

/**
 *  【身份实名认证】身份证二要素
 *  https://market.aliyun.com/products/57000002/cmapi00035880.html?spm=5176.2020520132.101.3.25a47218l9DwFs#sku=yuncode29880000015
 */
@Slf4j
public class IdentityVerify {

    /**
     * 身份二要素验证
     * @param name 姓名
     * @param idCard 身份证号码
     * @return
     */
    public static boolean verify(String name, String idCard){
        if (oConvertUtils.isEmpty(name) || oConvertUtils.isEmpty(idCard)) return false;
        String host = "https://dfidveri.market.alicloudapi.com";
        String path = "/verify_id_name";
        String method = "POST";
        String appCode = "4cd2142e6c4a49f18ea423cf7c294bd6";//阿里云账号：178900978@qq.com【程雷】
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appCode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("name", name);
        bodys.put("id_number", idCard);

        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            //log.info("===身份二要素验证=response==>{}", response.toString());
            //获取response的body
            String result = EntityUtils.toString(response.getEntity());
            //log.info("===身份二要素验证=result==>{}", result);
            log.info("===身份二要素验证=status==>{}", response.getStatusLine().getStatusCode());
            if (response.getStatusLine().getStatusCode() == 403) {
                log.info("===身份二要素验证调用频率超出限额==");
                return false;
            };
            //String转JSONObject
            if (oConvertUtils.isNotEmpty(result)) {
                JSONObject jsonObject = JSONObject.parseObject(result);
                if ("OK".equals(jsonObject.getString("status")) && jsonObject.getInteger("state")==1) return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static void main(String[] args) {

        System.out.println(verify("李猛", "88888888888888888"));

    }

}
